package com.lms.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.lms.bean.LabData;
import com.lms.bean.Root;
import com.lms.service.lab.LabService;
import com.lms.service.lab.LabServiceImpl;
import com.mysql.cj.util.StringUtils;
import com.lms.bean.Role;
import com.lms.bean.User;
import com.lms.service.root.RootService;
import com.lms.service.root.RootServiceImpl;
import com.lms.service.user.UserService;
import com.lms.service.user.UserServiceImpl;
import com.lms.util.Constants;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method=req.getParameter("method");
        if (method!=null){
            if (method.equals("pwdModify")){
                String oldpwd=req.getParameter("oldpwd");
                String newpwd=req.getParameter("newpwd");
                this.pwdModify(req,resp,oldpwd,newpwd);
            }else if (method.equals("ucexist")){
                this.userCodeExist(req,resp);
            }else if (method.equals("getLabList")){
                String local=req.getParameter("local");
                if (local!=null && local.equals("introduce")){
                    String from=req.getParameter("from");
                    if (from!=null && from.equals("user")){
                        this.getLabList(req,resp,"user/introduce.jsp");
                    }else if(from!=null && from.equals("root")){
                        this.getLabList(req,resp,"root/introduce.jsp");
                    }else {
                        /*url有误，转发至error*/
                        resp.sendRedirect(req.getContextPath()+"/error.jsp");
                    }
                }else if (local!=null && local.equals("apply")){
                    this.getLabList(req,resp,"user/apply.jsp");
                }else if (local!=null && local.equals("labAdm")){
                    this.getLabList(req,resp,"root/labAdm.jsp");
                }else{
                    /*url有误，转发至error*/
                    resp.sendRedirect(req.getContextPath()+"/error.jsp");
                }
            } else if (method.equals("getPersonalData")) {
                this.getPersonalData(req,resp);
            } else if (method.equals("getLabDataByLabName")){
                String labName = req.getParameter("labName");
                this.getLabDataByLabName(req,resp,labName);
            }else if (method.equals("getLabDataByLabCode")){
                String labCode = req.getParameter("labCode");
                this.getLabDataByLabCode(req,resp,labCode);
            }else if (method.equals("getCapacity")){
                String labCode = req.getParameter("labCode");
                String week = req.getParameter("week");
                String interval = req.getParameter("interval");
                this.getCapacity(req,resp,labCode,week,interval);
            }else if (method.equals("getLabCodeByLabName")){
                String labName = req.getParameter("labName");
                this.getLabCodeByLabName(req,resp,labName);
            } else{
                /*url有误，转发至error*/
                resp.sendRedirect(req.getContextPath() + "/error.jsp");
            }

        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /*personal:密码修改*/
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp,String oldpwd,String newpwd) throws ServletException, IOException {
        UserService userService = new UserServiceImpl();
        Map<String,String> map=new HashMap<>();
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);

        if (user!=null && user.getUserPassWord().equals(DigestUtils.md5Hex(Constants.SALT_HEAD+oldpwd+Constants.SALT_FOOT))) {
            if (userService.updatePwd(user.getUserCode(), newpwd)) {
                map.put("ok","yes");
            } else {
                map.put("ok","no");
            }
        }else {
            map.put("ok","no");
        }

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }


    /*在添加用户时判断添加的用户是否存在*/
    public void userCodeExist(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userCode = request.getParameter("userCode");
        HashMap<String,String> resultMap=new HashMap<>();

        if (StringUtils.isNullOrEmpty(userCode)){
            //空时，声明为存在
            resultMap.put("userCode","exist");
        }else {
            UserServiceImpl userService = new UserServiceImpl();
            User selectUser = userService.getUserByCode(userCode);/*此处待改！！*/
            if (selectUser!=null){
                resultMap.put("userCode","exist");
            }else {
                //查不到用户即表明不存在用户，可以添加
                resultMap.put("userCode","notexist");
            }
        }

        //将结果打入JSON，并输出
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

    /*获取实验室信息*/
    public void getLabList(HttpServletRequest request,HttpServletResponse response,String local) throws IOException, ServletException {
        List<LabData> labDataList =null;
        LabService labService=new LabServiceImpl();
        labDataList =labService.getLabList();

        request.setAttribute("labDataList", labDataList);
        /*回调本页*/
        request.getRequestDispatcher(local).forward(request,response);
    }

    /*personal：通过Session获取登录用户信息*/
    public void getPersonalData(HttpServletRequest request,HttpServletResponse resp) throws IOException {
        Map<String,String> map=new HashMap<>();
        User user=(User) request.getSession().getAttribute(Constants.USER_SESSION);
        if (user!=null) {
            map.put("userCode", user.getUserCode());
            map.put("userName", user.getUserName());
        }
        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*apply-details：通过labName获取labData*/
    public void getLabDataByLabName(HttpServletRequest req,HttpServletResponse resp,String labName) throws IOException {
        Map<String,Object> map=new HashMap<>();
        LabServiceImpl labService = new LabServiceImpl();

        map.put("labData",labService.getLabDataByLabName(labName));

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*apply-details：通过labCode获取labData*/
    public void getLabDataByLabCode(HttpServletRequest req,HttpServletResponse resp,String labCode) throws IOException {
        Map<String,Object> map=new HashMap<>();
        LabServiceImpl labService = new LabServiceImpl();

        map.put("labData",labService.getLabDataByLabCode(labCode));

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*查询当前实验室余量*/
    public void getCapacity(HttpServletRequest req,HttpServletResponse resp,String labCode,String week,String interval) throws IOException {
        Map<String,Object> map=new HashMap<>();
        LabServiceImpl labService = new LabServiceImpl();

        map.put("labTotal",labService.getLabTotalAndCapacity(labCode,week,interval)[0]);
        map.put("labCapacity",labService.getLabTotalAndCapacity(labCode,week,interval)[1]);

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    /*由labName获取labCode*/
    public void getLabCodeByLabName(HttpServletRequest req, HttpServletResponse resp,String labName) throws IOException {
        LabService labService = new LabServiceImpl();
        Map<String,Object> map = new HashMap<>();

        map.put("labCode",labService.getLabCodeByLabName(labName));

        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
}
